<template>
  <ul class="breadcrumb v-flex">
    <li
      v-for="item of breadcrumb"
      v-ripple
      class="breadcurmb-item v-radius"
      @click="onClickBreadcrumbItem(item)"
    >
      <!-- item是对象的 -->
      <span v-if="isObject(item)">{{ item[options.title] }}</span>
      <!-- item不是对象的 -->
      <span v-else>{{ item }}</span>
      <span class="breadcrumb-move v-radius"></span>
    </li>
  </ul>
</template>

<script lang='ts'>
import { computed, defineProps, PropType, defineComponent } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { isObject } from '@/utils';

interface IOptions {
  title: string,
  name: string,
  path: string
}

export default defineComponent({
  props: {
    replace: Boolean,
      // breadcrumb(面包屑)数组
      items: {
        type: Array as PropType<Array<String | IOptions>>,
        defualt: () => []
      },
      // 分隔符
      separator: {
        type: String,
        default: '/'
      },
      options: {
        type: Object as PropType<IOptions>,
        default: () => ({ title: 'title', name: 'name', path: 'path' })
      }
  },
  setup(props) {
    const route = useRoute();
    const router = useRouter();

    const breadcrumb = computed(() => {
      const routeList: Array<any> = (props.items?.length! > 0 ? props.items : (route.meta.breadcrumb || [])) as Array<any>;
      return routeList.reduce((prev: Array<any>, next: any, index: number, array: Array<any>) => {
        prev.push(next);
        if (index !== array.length - 1) {
          prev.push(props.separator);
        }
        return prev;
      }, [])
    });

    const onClickBreadcrumbItem = (item: any) => {
      if (isObject(item) && (item.path || item.name)) {
        item.name
          ? props.replace
            ? router.replace({ name: item.name })
            : router.push({ name: item.name })
          : props.replace
            ? router.replace({ path: item.path })
            : router.push({ path: item.path });
      }
    }
    return {
      route,
      router,
      breadcrumb,
      isObject,
      onClickBreadcrumbItem,
    }
  }
})

</script>

<style scoped lang="scss">
.breadcrumb {
  padding: 0 8px;
  font-size: 14px;
}
.breadcurmb-item {
  /* margin: 0 4px; */
  cursor: pointer;
  padding: 8px;
  transition: all 0.25s ease-out;
  position: relative;
}
.breadcurmb-item:hover {
  color: $primary-color;
}
.breadcrumb-move {
  display: inline-block;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: currentColor;
  transition: all 0.25s ease-out;
  opacity: 0;
  cursor: pointer;
}
.breadcurmb-item:hover .breadcrumb-move {
  opacity: 0.1;
}
</style>